#include "updatedialog.h"
#include "error.h"

extern bool isConfirmedByUser;

UpdateDialog::UpdateDialog(OtaHelperCli *updateCli, QWidget *parent) :
    QWidget(parent, Qt::WindowStaysOnTopHint)
{
	this->updateCli = updateCli;
    this->updateStatus = UpdateDialog::Stopped;

    this->setFixedSize(400, 250);
    this->setWindowIcon(QIcon("./excelfore.ico"));
    QGridLayout *mainlayout = new QGridLayout(this);
    mainlayout->setContentsMargins(0, 15, 0, 0);

    statusLabel = new QLabel(tr("等待升级..."), this);
    statusLabel->setStyleSheet("font-size:12px;");

    statusLabel->setMinimumWidth(400 - 2);
    statusLabel->setWordWrap(true);
    statusLabel->setAlignment(Qt::AlignVCenter | Qt::AlignCenter);

    infoView = new QTextEdit();
    QColor winColor = QWidget::palette().color(QPalette::Normal, QPalette::Window);
    infoView->setStyleSheet(QString("font-size:12px; background-color:rgb(%1, %2, %3)") \
                            .arg(winColor.red()).arg(winColor.green()).arg(winColor.blue()));
    infoView->setMinimumWidth(350);
    infoView->setMaximumHeight(200);
    infoView->setWordWrapMode(QTextOption::WordWrap);
    infoView->setReadOnly(true);
    infoView->verticalScrollBar()->show();
    infoView->hide();

    bookInstallButton = new QPushButton(tr("预约升级"));
    bookInstallButton->setMinimumSize(100, 30);
    bookInstallButton->setStyleSheet("font: bold \"Times New Roman\";font-size:12px;");
    bookInstallButton->setDefault(true);
    bookInstallButton->setEnabled(false);

    bookOkButton = new QPushButton(tr("OK"));
    bookOkButton->setMinimumSize(100, 30);
    bookOkButton->setStyleSheet("font: bold \"Times New Roman\";font-size:12px;");
    bookOkButton->setDefault(true);

    //dateEdit的属性设置：
    //QDateEdit *dateEdit = new QDateEdit(this);
    //dateEdit->setMinimumSize(20, 10);
    //dateEdit->setDateTime(QDateTime::currentDateTime());//显示日期设置
    //dateEdit->setDisplayFormat("yyyy/MM/dd");//显示格式设置

    //timeEdit的属性设置：
    //QTimeEdit *timeEdit = new QTimeEdit(this);
    //timeEdit->setMinimumSize(100, 100);
    //timeEdit->setDateTime(QDateTime::currentDateTime());//显示时间设置
    //timeEdit->setDisplayFormat ("HH:mm:ss");//显示格式设置

    selectMinutesBox = new QSpinBox(this);
    selectMinutesBox->setRange(1, 10000);
    selectMinutesBox->setSuffix(" mins");
    selectMinutesBox->setValue(0);
    selectMinutesBox->setMinimumWidth(160);

//    selectMinCombo = new QComboBox(this);
//    selectMinCombo->addItems(["%d mins" %x for x in range(1, 1000)]);
//    selectMinCombo->setMaxVisibleItems(10);
//    selectMinCombo->setInsertPolicy(QComboBox::InsertAfterCurrent);
//    selectMinCombo->setSizePolicy(QSizePolicy(160, 20));

//    QDoubleSpinBox
//    //selectMinCombo->setModel();
////    QAbstractListModel *listMode = new QAbstractListModel();
////    listMode->setR
////    QListWidget *listWidget = new QListWidget(selectMinCombo);
////    selectMinCombo->setModel(listWidget->model());
////    selectMinCombo->setView(listWidget);
////    QListWidgetItem* pitem = new QListWidgetItem(listWidget);
////    pitem->setSizeHint(QSize(listWidget->width(), 160));
////    listWidget->addItem(pitem);
////    pitem->setText("1");

    updateButton = new QPushButton(tr("现在升级"));
    updateButton->setMinimumSize(100, 30);
    updateButton->setStyleSheet("font: bold \"Times New Roman\";font-size:12px;");
    updateButton->setDefault(true);
    updateButton->setEnabled(false);

    quitButton = new QPushButton(tr("取消"));
    quitButton->setMinimumSize(100, 30);
    quitButton->setStyleSheet("font: bold \"Times New Roman\";font-size:12px;");
    quitButton->setAutoDefault(false);

    QWidget *buttonBoxBack = new QWidget(this);
    buttonBoxBack->setMinimumSize(385, 52);
    buttonBoxBack->setStyleSheet("background-color: rgb(224,223,227)");
    QGridLayout *buttonBoxBackLayout = new QGridLayout(buttonBoxBack);
    buttonBoxBackLayout->setContentsMargins(0, 0, 0, 0);

    QDialogButtonBox *buttonBox = new QDialogButtonBox;
    buttonBox->addButton(updateButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(bookInstallButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
    buttonBox->addButton(bookOkButton, QDialogButtonBox::ActionRole);
    buttonBoxBackLayout->addWidget(buttonBox, 0, 0, Qt::AlignCenter);

    progressBar = new QProgressBar(this);
    progressBar->setRange(0, 100);
    progressBar->setTextVisible(false);
    progressBar->hide();

	subProgressBar = new QProgressBar(this);
    subProgressBar->setRange(0, 100);
    subProgressBar->setTextVisible(false);
    subProgressBar->hide();

    QGridLayout *stsLayout = new QGridLayout();
    speedLabel = new QLabel("", this);
    speedLabel->hide();
    stsLayout->addWidget(statusLabel, 0, 0, Qt::AlignCenter);
    stsLayout->addWidget(speedLabel, 0, 1, Qt::AlignRight);

	errLabel = new QLabel(tr("..."), this);
    errLabel->setStyleSheet("color:rgb(224,20,10);font-size:12px;");
	errLabel->setFixedHeight(24);

    percentageLabel = new QLabel("", progressBar);
    percentageLabel->hide();

	subPercentageLabel = new QLabel("", subProgressBar);
    subPercentageLabel->hide();

    mainlayout->addWidget(infoView, 0, 0, 1, 65, Qt::AlignCenter | Qt::AlignBottom);
    mainlayout->addLayout(stsLayout, 1, 0, 1, 65, Qt::AlignCenter | Qt::AlignBottom);
    mainlayout->addWidget(subPercentageLabel, 2, 0, 1, 65, Qt::AlignCenter);
	mainlayout->addWidget(subProgressBar, 2, 0, 1, 65);
    mainlayout->addWidget(percentageLabel, 3, 0, 1, 65, Qt::AlignCenter);
    mainlayout->addWidget(progressBar, 3, 0, 1, 65);
    mainlayout->addWidget(selectMinutesBox, 3, 0, 1, 65);
    mainlayout->addWidget(buttonBoxBack, 4, 0, 1, 65);
	mainlayout->addWidget(errLabel, 4, 0, 1, 65, Qt::AlignLeft | Qt::AlignBottom);

    connect(updateButton, SIGNAL(clicked()), this, SLOT(onConfirmUpdate()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(onQuitButtonClicked()));
    connect(bookInstallButton, SIGNAL(clicked()), this, SLOT(onBookInstallClicked()));
    connect(bookOkButton, SIGNAL(clicked()), this, SLOT(onBookOkClicked()));

    setWindowTitle(tr("ecu升级"));

    connect(updateCli, SIGNAL(errStatusChanged(int, QString)), this, SLOT(onErrorStatusChanged(int, QString)), Qt::QueuedConnection);
    connect(updateCli, SIGNAL(popupWindow(int)), this, SLOT(onPopupWindowRequested(int)), Qt::QueuedConnection);
    connect(updateCli, SIGNAL(setProgressValue(int, QString)), this, SLOT(onProgressChanged(int, QString)), Qt::QueuedConnection);

    bookOkButton->hide();
    //selectMinutesBox->hide();
}

UpdateDialog::~UpdateDialog()
{
}

/*void UpdateDialog::updateStatusBar(QString sts)
{
    statusLabel->setText(sts);
    qApp->processEvents();

    if (!sts.isEmpty() && sts.contains(tr("正在更新"))) {
        isUpdating = true;
        quitButton->setEnabled(false);
        speedLabel->hide();
    }
}*/

void UpdateDialog::onErrorStatusChanged(int errCode, QString errString)
{
	errLabel->setText(errString);
	qApp->processEvents();
}

void UpdateDialog::onPopupWindowRequested(int windowId)
{
	QString sts = tr("升级成功！");
	switch (windowId) {
		case OtaHelperCli::INSTALL_NOW:
			sts = tr("升 级");
			updateButton->setEnabled(true);
			bookInstallButton->setEnabled(true);
		break;
		case OtaHelperCli::BOOK_INSTALL:
			sts = tr("预约升级");
		break;
		case OtaHelperCli::CHK_POL:
			sts = tr("车辆状态检测!");
		break;
		case OtaHelperCli::UPDATE_SUCCESS:
			sts = tr("升级成功！");
		break;
		case OtaHelperCli::UPDATE_FAIL:
			sts = tr("升级失败!");
		break;
		case OtaHelperCli::POLICY_FAIL:
			sts = tr("车辆检测失败!");
		break;
		case OtaHelperCli::PROGRESS_CHG:
			subPercentageLabel->setText(QString("current ecu: %1").arg(updateCli->current_percent));
			subProgressBar->setValue(updateCli->current_percent);
			percentageLabel->setText(QString("total: %1").arg(updateCli->total_percent));
			progressBar->setValue(updateCli->total_percent);
		break;
	}
	statusLabel->setText(sts);
	qApp->processEvents();
}

void UpdateDialog::onProgressChanged(int value, QString dnSpeed)
{
    progressBar->setValue(value);
    progressBar->update();
    percentageLabel->setText(QString("%1 \%").arg(value));
    speedLabel->setText(dnSpeed);
}

void UpdateDialog::onBookInstallClicked()
{
    statusLabel->setText(tr("预约升级..."));
    updateButton->hide();
    bookInstallButton->hide();
    selectMinutesBox->show();
    bookOkButton->show();
}

void UpdateDialog::onBookOkClicked()
{
    statusLabel->setText(tr("预约升级..."));
    updateButton->setEnabled(true);
    bookInstallButton->setEnabled(true);
    updateButton->show();
    bookInstallButton->show();
    selectMinutesBox->hide();
    bookOkButton->hide();

	updateCli->isClickOK = 1;
	selectMinutesBox->value();
	updateCli->booktime = selectMinutesBox->value();
	updateCli->userClicked((int)OtaHelperCli::BOOK_INSTALL);
	qApp->processEvents();

	qDebug() << "Book install Ok cliecked (" << updateCli->booktime << ")";
}

#if 0
void UpdateDialog::onRestartButtonClicked()
{
    statusLabel->setText(tr("正在重新启动..."));
    qApp->processEvents();
    this->updateHandler->restartTarget();
    this->close();
}
#endif

void UpdateDialog::onQuitButtonClicked()
{
	//qApp->processEvents();
	//exit(-11);
}

void UpdateDialog::onConfirmUpdate()
{
    statusLabel->setText(tr("开始升级..."));
    progressBar->show();
    updateButton->setEnabled(false);
    bookInstallButton->setEnabled(false);
    speedLabel->show();
    percentageLabel->show();

	//emit userClicked((int) OtaHelperCli::INSTALL_NOW);
	updateCli->isClickOK = 1;
	updateCli->userClicked((int)OtaHelperCli::INSTALL_NOW);
	qApp->processEvents();
}


